package com.dingding.study.Event.service;

import com.dingding.study.Event.DzjEventBus;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.SubscriberExceptionContext;
import com.google.common.eventbus.SubscriberExceptionHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class DefaultEventCenter implements EventCenter {


    private EventBus eventBus;

    private String name;

    public DefaultEventCenter(String eventCenterName) {
        this.name = eventCenterName;
        this.eventBus = new DzjEventBus(new DefaultEventExceptionHandler());
    }

    @Override public <T extends Event> void publish(T event){
        eventBus.post(event);
    }

    @Override public <T extends EventListener<?>> void subscribe(T listener) {
        eventBus.register(listener);
    }

    public String getName() {
        return name;
    }

    class DefaultEventExceptionHandler implements SubscriberExceptionHandler {

        @Override
        public void handleException(Throwable exception, SubscriberExceptionContext context) {
            Object event = context.getEvent();
            log.error("[event center {}]:event {} process failure", name, event,exception);
            throw new EventProcessException(exception);
        }

    }
}
